package cn.tedu.csmall.passport.service.impl;

import cn.tedu.csmall.passport.ex.ServiceException;
import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.dto.AdminLonginDTO;
import cn.tedu.csmall.passport.pojo.entity.Admin;
import cn.tedu.csmall.passport.pojo.dto.AdminAddNewDTO;
import cn.tedu.csmall.passport.pojo.vo.AdminListItemVO;
import cn.tedu.csmall.passport.pojo.vo.AdminStandardVO;
import cn.tedu.csmall.passport.service.IAdminService;
import cn.tedu.csmall.passport.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * ClassName: AdminServiceImpl
 * Package: cn.tedu.csmall.passport.service.impl
 * Description 处理管理员业务实体类
 *
 * @version 0.0.1
 * @Author: 大傻
 * @Create:2022/12/8
 */
@Service
@Slf4j
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    public AdminServiceImpl(){
        log.debug("创建业务对象: AdminServiceImpl");
    }

    @Override
    public void login(AdminLonginDTO adminLonginDTO) {
        log.debug("开始处理管理员登录的业务,参数{}",adminLonginDTO);
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                adminLonginDTO.getUsername(),adminLonginDTO.getPassword()
        );
        Authentication authenticateResult = authenticationManager.authenticate(authentication);
        log.debug("认证通过!");
        log.debug("认证结果：{}", authenticateResult); // 注意：此认证结果中的Principal就是UserDetailsServiceImpl中返回的UserDetails对象
        // 将认证通过后得到的认证信息存入到SecurityContext中
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authenticateResult);
    }

    @Override
    public void addNew(AdminAddNewDTO adminAddNewDTO) {
        log.debug("开始处理添加管理员的业务,添加管理员参数:{}",adminAddNewDTO);
        String userName= adminAddNewDTO.getUsername();
        int countByUserName = adminMapper.countByUserName(userName);
            if (countByUserName>0){
                String message = "添加管理员失败,用户名重复请更换";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
            }
        int countByPhone = adminMapper.countByPhone(adminAddNewDTO.getPhone());
            if (countByPhone>0){
                String message = "添加管理员失败,手机号码重复请更换";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
            }
        int countByEmail = adminMapper.countByEmail(adminAddNewDTO.getEmail());
            if (countByEmail>0){
                String message = "添加管理员失败,邮箱重复请更换";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
            }
        Admin admin = new Admin();
        //数据创建时间
        admin.setGmtCreate(LocalDateTime.now());
        BeanUtils.copyProperties(adminAddNewDTO,admin);
        String rawPassword = admin.getPassword();
        String encodePassword = passwordEncoder.encode(rawPassword);
        admin.setPassword(encodePassword);
        admin.setLoginCount(0);
        adminMapper.insert(admin);
        log.debug("添加管理员成功，管理员参数{}",admin);

    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理根据ID删除管理员业务,参数{]",id);
        AdminStandardVO queryResult = adminMapper.getStandardById(id);
        if (queryResult==null){
            String massage= "删除管理员失败,尝试访问的数据不存在!";
            log.debug(massage);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,massage);
        }
        log.debug("即将执行删除,参数:{}",id);
         adminMapper.deleteById(id);
    }

    @Override
    public void setEnable(Long id) {
        updateEnableById(id,1);
    }

    @Override
    public void setDisable(Long id) {
        updateEnableById(id,0);
    }

    @Override
    public List<AdminListItemVO> list() {
        log.debug("开始处理【查询管理员列表】的业务，参数：无");
        List<AdminListItemVO> list = adminMapper.list();
        return list;
    }

    private void updateEnableById(Long id,Integer enable){
        String[] enableText = {"禁用","启用"};
        log.debug("开始处理" + enableText[enable] + "管理员的业务，管理员ID：{}，目标状态：{}", id, enable);
        AdminStandardVO queryResult = adminMapper.getStandardById(id);
        if (queryResult==null){
            String message=enableText[enable]+"管理员失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        // 检查管理员数据的当前状态是否与参数enable表示的状态相同
        if (queryResult.getEnable()==enable){
            String message = enableText[enable] + "管理员失败，当前管理员已经是"
                    + enableText[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        Admin admin = new Admin();
        admin.setId(id);
        admin.setEnable(enable);
        log.debug("即将修改数据，参数：{}", admin);
        adminMapper.update(admin);
    }

}
